import { ElMessageBox } from "element-plus/es";
import { EleMessage } from "ele-admin-plus/es";
import { useSubmitHook } from "./useSubmitHook";
import { useTable } from "./useTable"; // 引入useTable

/**
 * 使用操作功能的钩子
 * @param {Object} options - 配置选项
 * @param {Object} options.actionConfigs - 操作配置，包含不同操作（如删除、更新）的配置
 * @param {Array} options.selections - 选中的数据项
 * @param {String} [options.idField="id"] - 数据项的唯一标识字段
 * @param {String} [options.idName="dict_data_name"] - 数据项的显示名称字段
 * @param {Function} [options.reload] - 重新加载数据的函数
 * @param {Object} props - 组件属性
 * @param {Function} emit - 事件触发函数
 * @returns {Object} - 返回操作函数
 */
export function useOperator(options, props = {}, emit = {}) {
  const {
    actionConfigs,
    selections,
    idField = "id",
    idName = "dict_data_name",
    reload,
    // 删除最外层的 skipConfirm
  } = options;

  const { handleBeforeSubmit, handleAfterSubmit, handleSubmitError } =
    useSubmitHook();
  const { loading } = useTable(); // 使用useTable中的loading

  // 封装设置loading状态的函数
  const setLoading = (value) => {
    loading.value = value;
  };

  const action = (type = "remove", row, data = {}) => {
    const rows = row == null ? selections.value : [row];
    if (!rows.length) {
      EleMessage.error("请至少选择一条数据");
      return Promise.resolve();
    }

    const config = actionConfigs[type] || {};
    console.log(data.statusText, "data.statusText");

    // 从 actionConfigs 中获取 skipConfirm
    const skipConfirm = config.skipConfirm || false;

    // 简化获取 desc 的逻辑
    const desc = data?.statusText || "";
    const confirmText = (
      config.confirmText ||
      `确定要${config.title || "操作"}“${rows.map((d) => d[idName]).join(", ")}”吗?`
    ).replace(/\{%s\}/g, desc + rows.map((d) => d[idName]).join(", "));

    let operationPromise;
    if (skipConfirm) {
      // 跳过确认弹框，直接执行操作
      operationPromise = Promise.resolve();
    } else {
      operationPromise = ElMessageBox.confirm(confirmText, "系统提示", {
        type: "warning",
        draggable: true,
      });
    }

    return operationPromise
      .then(() => {
        setLoading(true); // 使用封装后的函数

        const apiFunc = config.api;

        if (!apiFunc) {
          setLoading(false);
          return Promise.reject(new Error("未找到对应的API方法"));
        }

        const idFields = rows.map((d) => d[idField]);
        const formData = {
          [idField]: idFields,
          ...data,
        };
        console.log("formData", formData);
        return handleBeforeSubmit(config, {
          type,
          rows,
          formData,
        })
          .then((modifiedData) => {
            return apiFunc(modifiedData.formData || modifiedData);
          })
          .then((result) => {
            handleAfterSubmit(config, { type, rows, result });
            setLoading(false);
            EleMessage.success(result);
            reload?.();
            return result;
          })
          .catch((e) => {
            setLoading(false);
            console.error("操作失败:", e);
            if (!e.message) {
              e.message = e.toString();
            }
            EleMessage.error(e.message);
            handleSubmitError(config, e);
            throw e;
          });
      })
      .catch(() => {
        setLoading(false);
        return Promise.resolve();
      });
  };

  return { action };
}
